package com.yjf.ljr.parser;

import java.lang.reflect.Field;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
 * 数据基类
 */
public abstract class DataClass {

	// 返回结果代码
	@Expose
	@SerializedName("code")
	public String code;

	@Expose
	@SerializedName("message")
	public String msg;

	/**
	 * 解析Json字符串, copy实现赋值
	 * 
	 * @param str
	 *            被解析的字符串
	 */
	public void getDataClassFromStr(String str) {
		try {
			if (!TextUtils.isEmpty(str)) {
				GsonBuilder builder = new GsonBuilder();
				Gson gson = builder.excludeFieldsWithoutExposeAnnotation().create();
				DataClass valueObject = (DataClass) gson.fromJson(str, this.getClass());
				copy(valueObject);
			}
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 属性拷贝 将 dataClassSrc的 属性值拷贝到当前对象上
	 * 
	 * @param dataClassSrc
	 *            数据源
	 */
	public boolean copy(DataClass dataClassSrc) {
		if (dataClassSrc == null) {
			return false;
		}
		this.code = dataClassSrc.code;
		this.msg = dataClassSrc.msg;

		// 为当前对象赋值
		Class<?> clazz = dataClassSrc.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			try {
				field.set(this, field.get(dataClassSrc));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return true;
	}
}